# -*- coding: UTF-8 -*-

import pymysql
import requests
import json
import threading
import time
from datetime import datetime

# 接口地址
BASE_CURRENCY = 'usdt'
# 现货
APIBASE_CASH = "https://api.huobi.pro"
API_CASHKLINE = "/market/history/kline?period=1day&size=1&symbol=%s"
CASH_SYMBOL = ['btc','eth','ltc','eos','xrp','etc','bch','bsv','ada']
# 合约
APIBASE_CONTRACT = "https://api.hbdm.com"
API_ALL_SYMBOL = "/api/v1/contract_contract_info"
API_CONTRACT_KLINE = "/market/history/kline?period=1day&size=1&symbol=%s"



'''
先判断当前是否周五下午，是则表示要取交割数据
'''
now = time.localtime(time.time())
print(now.tm_wday)
if now.tm_wday==4 and now.tm_hour>=16 and now.tm_hour<=18:
	isDone = True
	count = 0
	while isDone:# 若未交割完成，则循环查询
		# 获取合约状态
		r = requests.get(APIBASE_CONTRACT + API_ALL_SYMBOL)
		dataObj = json.loads(r.text)
		items = dataObj['data']
		
		for item in items:
			isDone = item['contract_status']==1
			if not isDone:
				break
		isDone = not isDone
		count = count + 1
		if count>=800:
			exit()  # 防止超时，永久循环
		print("交割未完成...%s"%count)
		time.sleep(10)

#cache
all_data = []

# cash data ========================================
#请求数据函数
def getCashKlineData(symbol, url):
	r = requests.get(url)
	dataObj = json.loads(r.text)
	items = dataObj['data']
	row = {'symbol':symbol, 'klinedata':json.dumps(items[0])}
	all_data.append(row)
	#print(items[0])
#分配线程
tasks = []
for coin_symbol in CASH_SYMBOL:
	newUrl = APIBASE_CASH + API_CASHKLINE%(coin_symbol) + 'usdt'
	t = threading.Thread(target=getCashKlineData,args=(coin_symbol,newUrl))
	tasks.append(t)
#start the thread
for t in tasks:
	t.setDaemon(True)
	t.start()
	time.sleep(0.2)
#wait for complete
for t in tasks:
	t.join()
#for i in all_data:
#	print(i['symbol']+","+i['klinedata'])

# contract data ======================================
# request contract kline data
def getContractKlineData(symbol,url):
	#print(url)
	r = requests.get(url)
	dataObj = json.loads(r.text)
	items = dataObj['data']
	symbol['klinedata'] = json.dumps(items[0])
	all_data.append(symbol)
	#print(symbol)

contract_symbol = []
# get symbol
r = requests.get(APIBASE_CONTRACT + API_ALL_SYMBOL)
dataObj = json.loads(r.text)
items = dataObj['data']
for item in items:
	symbol_obj = {'symbol':item['symbol'],'contractcode':item['contract_code'],'contracttype':item['contract_type']}
	contract_symbol.append(symbol_obj)
# get kline data
ctasks = []
for symbol in contract_symbol:
	#print("symbol:"+symbol['symbol']+",code:"+symbol['contractcode']+",type:"+symbol['contracttype'])
	req_symbol = symbol['symbol'] + '_CW'
	if symbol['contracttype']=='next_week':
		req_symbol = symbol['symbol'] + '_NW'
	elif symbol['contracttype']=='quarter':
		req_symbol = symbol['symbol'] + '_CQ' 

	newUrl = APIBASE_CONTRACT + API_CONTRACT_KLINE%(req_symbol)
	t = threading.Thread(target=getContractKlineData, args=(symbol, newUrl))
	ctasks.append(t)
for t in ctasks:
	t.setDaemon(True)
	t.start()
	time.sleep(0.2)
#wait for complete
for t in ctasks:
	t.join()


#  put into db ==============================================================
# 插入数据库
conn = pymysql.connect(host="211.149.242.97",user="cyptcryKline",password="EwdKHBk2zyRKbbiy",database="cyptcryKline",charset="utf8")
cursor = conn.cursor()

sql = "INSERT INTO kline (symbol, contractcode, contracttype, klinedata, rectime) VALUES (%s,%s,%s,%s,CURRENT_TIMESTAMP)"
vals = []
for row in all_data:
	code = ''
	if 'contractcode' in row.keys():
		code = row['contractcode']
	ctype = ''
	if 'contracttype' in row.keys():
		ctype = row['contracttype']
	vals.append((row['symbol'], code, ctype,row['klinedata']))

try:
	cursor.executemany(sql, vals)
	conn.commit()
except Exception as e:
	conn.rollback()

cursor.close()
conn.close()

print("It's done!")

